<?php
/**
 * 使用示例
 * @author M2
 * @version 1.0
 * create Date 2013-11-11
 * <yl:contents><yl:content type="title"/></yl:contents>
 */
//YlPageChannelsTaglib
class YlPageContentsTaglib {
    private $nowPage = 1;
    private $count = 0;
    private $pagesize = 20;
    private $totalPage = 0;
    private $_dbPrefix = 'yl_';
    
    /**
     * 每次生成的页面的数量限制
     */
    private $_pageLimit = 100;
	public function __construct() {
		C(include SITE_PATH.'/extends/taglib/tagarr.php');
                C(require APPS_PATH.'/cms/Conf/config.php');
                $dbPrefix = C('DB_PREFIX');
                !empty($dbPrefix) && $this->_dbPrefix = $dbPrefix;
	}
	public function parse($content,$cateid,$siteid,$channels,$templatePath,$domain,$channel, $catenaming,$token='') {
        if (stripos($content, 'yl:pagecontents') !== false) {
            $matches = preg_parse($content, 'yl:pageContents');
            $channelname = getParseOneAttr($matches[0], 'channelname');
            $groupchannel = getParseOneAttr($matches[0], 'groupchannel');
            $pagesize = getParseOneAttr($matches[0], 'pagesize');
            $scope = getParseOneAttr($matches[0], 'scope');
            $order = getParseOneAttr($matches[0], 'order');
            // add by jepin 20140904
            $where = getParseOneAttr($matches[0], 'where');
            
            if (!empty($channelname)) {
                //update next 2013-12-12 增加单栏目标签缓存
                if (($arrcategory = S('cache_channelname_'.$siteid.'_'.$channelname)) === false) {
                    $arrcategory = M('cms_category')
                        ->field('(case when url <> "" then url when createurl <> "" then createurl
	                            else (concat("'.$domain.'","/",replace(replace((case when catenaming <> ""
	                		 then catenaming else ("'.$channel['catenaming'].'") end),"{cateid}",id),"{@ChannelID}",id))) end) as url,
	                            replace(imageurl,"@","'.$domain.'") as imageurl,id,cname,content,keywords,
	                            description')
                        ->where('siteid = '.$siteid.' and cname="'.$channelname.'"')
                        ->find();
                    S('cache_channelname_'.$siteid.'_'.$channelname, $arrcategory);
                }
                $cateid=$arrcategory['id'];
            }

            $data['siteid'] = $siteid;
            $data['cid'] = $cateid;
            $this->pagesize = $pagesize?$pagesize:$this->pagesize;//获取并设置每页显示多少条
            $artnamingsql='"'.$channel['artnaming'].'"';
            $artnamingid="";
            
            //add tony 2014-9-29 增加内容列表项中栏目分组
            if (!empty($groupchannel)) {
                $data = "siteid=".$siteid." and  `status` = 1  AND INSTR((select CONCAT(',',w.group_name_collection,',') FROM ".$this->_dbPrefix."cms_category w WHERE w.id=cid),'," . $groupchannel . ",')>0";
            }else{
                if (strtolower($scope) === 'all') {
                    //add next 2013-12-12  增加得到子栏目列表的缓存,过期300秒
                    if (($gcate = S('cache_childcate_'.$cateid)) === false) {
                        $gcate = D('Category')->getChildCate($cateid);
                        
                        S('cache_childcate_'.$cateid, $gcate,300);
                    }
                    $data = 'siteid='.$siteid.' and  `status` = 1 and (cid='.$cateid.' or FIND_IN_SET( cid, "'.$gcate.'" ))';
                    !empty($where) && $data .= 'and '.$where;
                    
                    //是否只有一个栏目ID,就保存起来
                    if(strpos($gcate,',')<=0) {
                        $artnamingid=$gcate;
                    }
                }else{
                    //只有一个栏目ID,就保存起来
                    $artnamingid=$cateid;
                }
            }
            //add next 2013-12-11 增加得到栏目生成内容规划的判断
            if (!empty($artnamingid)) {
                if ($category_list = S('cache_channel_'.$artnamingid) === false) {
                    $category_list = M('cms_category')->where('id='.$artnamingid)->find();
                    S('cache_channel_'.$artnamingid, $category_list);
                }
                if(!empty($category_list['artnaming'])){
                    $artnamingsql='"'.$category_list['artnaming'].'"';
                }
            }else{
                $artnamingsql='(select (case when B.artnaming <> "" then B.artnaming else ("'.$channel['artnaming'].'") end) from '.$this->_dbPrefix.'cms_category B where B.id=cid)';
            }

            if(!$this->count){
                $this->count = M('cms_article article')->where($data)->count(); //统计当前栏目下的所有内容总数
                S('cache_channel_pageTotal_'.$cateid,$this->count);
            }
            $order = $order?$order.' desc':'updatetime desc';
            $this->totalPage = ceil($this->count/$this->pagesize); //总页数
            if($this->nowPage >= $this->totalPage) $this->nowPage = $this->totalPage; //如果当前页大于总页数，就让当前页=总页数
            if($this->nowPage<=1) $this->nowPage = 1; //如果当前页小于1，当前页=1

            if(!($result = S('cache_channel_result_'.$cateid))){
                $result = M('cms_article')
                    ->field('(case when url <> "" then url else
                        (concat("'.$domain.'","/",replace(replace('.$artnamingsql.',"{cateid}",
                        cid),"{contentid}",id))) end) as url,
                        replace(imageurl,"@","'.$domain.'") as imageurl,replace(big_imageurl,"@","'.$domain.'") as big_imageurl,title,summary,group_name_collection,
                    subtitle,author,updatetime,inputtime,tags ,source,content,comment_count,readpoint,keywords,cid,id,siteid,description,create_uid,create_uname,update_uid,update_uname,fileurl')
                    ->where($data)->order($order)->select(); //获取内容列表;
                $error = M('cms_article')->getError();
                $sql = M('cms_article')->getLastSql();
                S('cache_channel_result_'.$cateid,$result);
            }
            //判断总页数是否大于每次生成的页面数量
            if($this->totalPage > $this->_pageLimit){
                //分为多次处理
                //当前栏目已经接受的处理请求的次数
                if(false === ($createCount = S('cache_channel_create_count'.$cateid.$token,'',null,'File',C('CREATE_CACHE_OPTION')))){
                    $createCount = 0;
                }
                $start = 1+$createCount*$this->_pageLimit;
                if($this->totalPage<($createCount+1)*$this->_pageLimit){
                    $end = $this->totalPage;
                }else{
                    $end = $start + $this->_pageLimit - 1;
                }
            }else{
                $start = 1;
                $end = $start + $this->totalPage - 1;
            }
            for($i=$start;$i<=$end;$i++) {
                $this->nowPage = $i;
                $startPage = $this->pagesize * ($this->nowPage -1); //获取起始页
                $list = array_slice($result, $startPage, $this->pagesize);
                $parseStr = '';
                $pageContentsText = getParseContentText($matches[0], 'yl:pageContents');
                if(!empty($list)) {
                    foreach ($list as $k => $v) {
                        S('cache_contents_'.$v['id'], $v);
                        //update next 2013-12-12 简化替换操作
                        $text = taglib(C('yl:if'))->parse($pageContentsText, $v);
                        $text = taglib(C('yl:a'))->parse($text,$siteid,$v,'1',$domain,$channel);
                        $text = taglib(C('yl:content'))->parse($text,$v,$domain);
                        $text = taglib(C('yl:image'))->parse($text,$v);
                        $text = taglib(C('yl:count'))->parse($text,$v);

                        if(strpos($text,'{') && strpos($text,'}')) {
                            //big bug <fixed by tony 2014-9-26>
                            preg_match_all('/\{Content\.(.*?)\}/eis',$text,$out);
                            for ($j=0; $j< count($out[0]); $j++) {
                                $text = str_ireplace($out[0][$j],$v[$out[1][$j]],$text);
                            }
                        }
                        $parseStr .= $text;
                    }
                } else {
                    $parseStr = '';
                }
                $pageContent = str_replace($matches[0], $parseStr, $content);
                if($this->totalPage==1){
                     $matchItems = preg_parse($pageContent, 'yl:pageItems');
                     foreach($matchItems as $fp) {
                         $pageContent = str_replace($fp, "", $pageContent);
                     }
                }else{
                    $matchItems = preg_parse($pageContent, 'yl:pageItems');
                    foreach($matchItems as $fp) {
                        $text = getParseContentText($fp, 'yl:pageItems');
                        $matchesPageItem = preg_parse($text, 'yl:pageItem');
                        foreach($matchesPageItem as $epageitem) {
                            $text = taglib(C('yl:pageitem'))->parse($epageitem,$channels,$this->count,$this->pagesize,$this->nowPage,$domain);
                            $pageContent = str_replace($epageitem, $text, $pageContent);
                        }
                        $qtext = getParseContentText($fp, 'yl:pageItems');
                        $pageContent = str_replace($fp, $qtext, $pageContent);
                    }
                   }    
                $arr = explode('.',$catenaming);
                if($this->nowPage == 1)
                    $contents['catenaming'] = $arr[0].'.'.$arr[1];
                else
                    $contents['catenaming'] = $arr[0].'_'.$this->nowPage.'.'.$arr[1];

                if(dirname($templatePath.$contents['catenaming']))
                    mk_dir(dirname($templatePath.$contents['catenaming']));

                $path = $templatePath.$contents['catenaming'];
                $pageContent = taglib('YlA')->parse($pageContent,$siteid,$channels,'1', $domain, $channel);
                $pageContent = taglib('YlImage')->parse($pageContent, $channels);
                $pageContent = taglib('YlChannel')->parse($pageContent,$channels, $siteid, $domain, $channel);

                file_put_contents($path,$pageContent);
            }
            
            //判断总页数是否大于每次生成的页面数量
            if($this->totalPage > $this->_pageLimit){
                //当前栏目已经接受的处理请求的次数
                if($this->totalPage<=($createCount+1)*$this->_pageLimit){
                    //完成后销毁缓存
                    S('cache_channel_create_count'.$cateid.$token,null,null,'File',C('CREATE_CACHE_OPTION'));
                    return 'complete';
                }else{
                    S('cache_channel_create_count'.$cateid.$token,$createCount + 1,null,'File',C('CREATE_CACHE_OPTION'));
                    return 'uncomplete';
                }
            }else{
                return 'complete';
            }
        }
        return $content;
	}
}
